﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Animator))]
public class SheepController : MonoBehaviour {
    public static bool IsShear { get; set; }

    public Animator animator;
    public GameObject effect;
    public GameObject woolEffect;

	void Start() {
        if (animator == null) {
            animator = GetComponent<Animator>();
        }

        Run();
	}

    GameAudioSource _lastSpeakAudio;

    void OnMouseDown() {
        if (_lastSpeakAudio != null) {
            _lastSpeakAudio.Stop();
        }

        Speak();
        var stateInfo = animator.GetCurrentAnimatorStateInfo(0);
        _lastSpeakAudio = AudioManager.Instance.PlaySound(AdditionResPath.VOICE_SHEEP_SPEAK);

        if (IsShear) {
            GetComponent<BoxCollider>().enabled = false;
            effect.SetActive(false);
            woolEffect.SetActive(true);
            transform.Find("Wool").SetActive(false);
            AudioManager.Instance.PlaySound(AdditionResPath.SE_SHERA);
            AdditionManager.Instance.ShowWoolAndNum(transform.position);

            StartCoroutine(TimeUtility.DelayInvoke(_lastSpeakAudio.Length, () => {
                Run();
                var endPos = transform.localPosition + (transform.right * 1000f);
                transform.DOLocalMove(endPos, AdditionManager.Instance.sheepRunTime).OnComplete(() => Destroy(gameObject));
            }));
        }      
    }

    public void Run() {
        animator.CrossFade("Run", 0.1f);
    }

    public void Speak() {
        animator.Play("Speak", -1, 0f);
    }

    public void Idle() {
        animator.CrossFade("Idle", 0.1f);
    }
}
